/**
 *  日志相关操作的接口
 * 
 */
const express = require("express")
const router = express.Router()
const pool = require("../../db/db.js")
const Response = require("../../utils/ResponseData.js")

// 首页查询最新三条日志
router.get("/queryThree", (req, res, next) => {
    // 编写sql(最新的数据,id最大)
    const sql = "select * from pet_diary order by d_id desc limit 0,3"
    // 执行sql
    pool.query(sql, (err, data) => {
        if (err) {
            console.log("/queryThree", err);
            next(err)
            return
        }
        if (data.length > 0) {
            res.send(Response.success(data, "日志查询成功"))
        } else {
            res.send(Response.error("日志查询失败"))
        }
    })
})
// 查询全部日志
router.get("/queryAll/:page/:pageSize", (req, res, next) => {
    // 获取请求参数
    let { page, pageSize } = req.params
    // 编写sql
    let startIndex = (page - 1) * pageSize
    pageSize = parseInt(pageSize)
    const sql = "select * from pet_diary order by d_id desc limit ?,?"
    pool.querySync(sql, [startIndex, pageSize])
        .then(result => {
            if (result.length > 0) {
                res.send(Response.success(result, "日志查询成功!"))
            } else {
                res.send(Response.error("日志查询失败!"))
            }
        }).catch(err => {
            if (err) {
                console.log("/queryAll", err);
                next(err)
                return
            }
        })
})
// 通过日志id查询
router.get("/queryById/:id", (req, res, next) => {
    // 编写sql(最新的数据,id最大)
    let { id } = req.params
    const sql = "select * from pet_diary where d_id = ?"
    // 执行sql
    pool.query(sql, [id], (err, data) => {
        if (err) {
            console.log("/queryById/:id", err);
            next(err)
            return
        }
        if (data.length > 0) {
            res.send(Response.success(data, "日志查询成功"))
        } else {
            res.send(Response.error("日志查询失败"))
        }
    })
})
module.exports = router